from rest_framework import serializers
from rest_framework.fields import SerializerMethodField
from rest_framework.serializers import ModelSerializer

from community.models import *


class LabelSerializer(ModelSerializer):
    class Meta:
        model = Label
        fields = "__all__"


class ArticleSerializer(ModelSerializer):
    # 添加用户名字段显示
    user_name = serializers.CharField(source='user.username', read_only=True)
    # 添加用户头像字段显示
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)

    class Meta:
        model = Article
        exclude = ["is_delete"]

        extra_kwargs = {
            "page_view": {"read_only": True},
            "priority": {"read_only": True}
        }


class CommentSerializer(ModelSerializer):
    # 添加用户名字段显示
    user_name = serializers.CharField(source='user.username', read_only=True)
    # 添加用户头像字段显示
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)
    # 子级评论的总数
    son_comment_count = SerializerMethodField(read_only=True)

    class Meta:
        model = Comment
        exclude = ["is_delete"]

    #SerializerMethodField允许我们自定义一个方法里计算或者获取该字段的值
    #get_字段名
    def get_son_comment_count(self, comment):
        return comment.parent_comment_set.count()


class SonCommentSerializer(ModelSerializer):
    # 添加用户名字段显示
    user_name = serializers.CharField(source='user.username', read_only=True)
    # # 添加用户头像字段显示
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)
    reply_username = serializers.CharField(source='reply_comment.user.username', read_only=True)


    class Meta:
        model = Comment
        exclude = ["is_delete"]
